<template>
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="活动名称" prop="politeName">
        <el-input v-model="formData.politeName" placeholder="请输入活动名称" />
      </el-form-item>
      
      <el-form-item label="报名时间" prop="signTime">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      
      <el-form-item label="活动内容" prop="content">
        <el-input 
          v-model="formData.content" 
          type="textarea" 
          placeholder="请输入活动内容" 
          :rows="3" 
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { addPoliteActivity, updatePoliteActivity, getPoliteDetail } from '@/api/active/active_polite'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  }
})

// 定义emits
const emit = defineEmits(['update:visible', 'success'])

// 表单相关
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const formData = ref({
  id: undefined as number | undefined,
  politeName: '',
  signTime: '',
  time: '',
  content: '',
  shops: 0,
  products: 0
})

// 时间范围
const timeRange = ref<[string, string]>(['', ''])

// 表单验证规则
const formRules = {
  politeName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  signTime: [
    { required: true, validator: validateTimeRange, trigger: 'change' }
  ]
}

// 验证时间范围
function validateTimeRange(rule: any, value: any, callback: any) {
  if (!timeRange.value[0] || !timeRange.value[1]) {
    callback(new Error('请选择活动时间'))
  } else {
    callback()
  }
}

// 对话框标题
const dialogTitle = computed(() => {
  return props.editData ? '编辑白名单活动' : '新增白名单活动'
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emit('update:visible', val)
  }
})

// 监听editData变化
watch(() => props.editData, (newVal) => {
  if (newVal) {
    // 编辑模式
    formData.value = {
      id: newVal.id,
      politeName: newVal.politeName || '',
      signTime: newVal.signTime || '',
      time: newVal.time || '',
      content: newVal.content || '',
      shops: newVal.shops || 0,
      products: newVal.products || 0
    }
    
    // 设置时间范围
    if (newVal.signTime) {
      const times = newVal.signTime.split('~');
      if (times.length === 2) {
        timeRange.value = [times[0], times[1]];
      }
    }
  } else {
    // 新增模式
    formData.value = {
      id: undefined,
      politeName: '',
      signTime: '',
      time: '',
      content: '',
      shops: 0,
      products: 0
    }
    timeRange.value = ['', '']
  }
}, { immediate: true })

// 获取活动详情
const getDetail = (id: number) => {
  getPoliteDetail({ id }).then((res: any) => {
    const data = res.data
    formData.value = {
      id: data.id,
      politeName: data.politeName || '',
      signTime: data.signTime || '',
      time: data.time || '',
      content: data.content || '',
      shops: data.shops || 0,
      products: data.products || 0
    }
    
    // 设置时间范围
    if (data.signTime) {
      const times = data.signTime.split('~');
      if (times.length === 2) {
        timeRange.value = [times[0], times[1]];
      }
    }
  }).catch(() => {
    ElMessage.error('获取活动详情失败')
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      
      // 更新表单数据的时间字段
      formData.value.signTime = timeRange.value[0] + '~' + timeRange.value[1];
      
      const submitFunc = props.editData ? updatePoliteActivity : addPoliteActivity
      
      submitFunc(formData.value).then(() => {
        ElMessage.success(props.editData ? '编辑成功' : '新增成功')
        submitLoading.value = false
        handleClose()
        emit('success')
      }).catch(() => {
        ElMessage.error(props.editData ? '编辑失败' : '新增失败')
        submitLoading.value = false
      })
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 暴露方法给父组件
defineExpose({
  getDetail
})
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>